package com.yanx.system.web.infra.listener;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.yanx.common.command.executor.CommandExecutor;
import com.yanx.common.core.dto.OperationLogDto;
import com.yanx.common.core.event.OperationLogEvent;
import com.yanx.common.security.SecurityUtils;
import com.yanx.common.utils.Address_;
import com.yanx.system.base.command.MonOperLogCreateCmd;
import com.yanx.system.base.model.dto.MonOperLogDto;
import com.yanx.system.web.infra.mapper.MonitorOperLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author gotanks
 * @create 2022/9/13
 */
@Slf4j
@Component
public class OperationLogListener implements ApplicationListener<OperationLogEvent> {

    @Autowired
    private CommandExecutor commandExecutor;

    @Async
    @Override
    public void onApplicationEvent(OperationLogEvent event) {
        OperationLogDto operationLogDto = (OperationLogDto) event.getSource();

        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null) {
            operationLogDto.setOperName(loginUser.getUsername());
        }

        //远程查询操作地点
        operationLogDto.setOperLocation(Address_.getRealAddressByIP(operationLogDto.getOperIp()));

        MonOperLogDto monOperLogDto = MonitorOperLogMapper.INSTANCE.toMonOperLogDto(operationLogDto);
        commandExecutor.execute(new MonOperLogCreateCmd(monOperLogDto));
    }
}
